package com.github.chirspan.xaas.auth.service;

import com.github.chirspan.xaas.auth.integration.IntegrationAuthentication;
import com.github.chirspan.xaas.auth.integration.IntegrationAuthenticationContext;
import com.github.chirspan.xaas.auth.integration.authenticator.IntegrationAuthenticator;
import com.github.chirspan.xaas.security.service.AuthUserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ChenPan
 * @date 2018/6/25 11:27
 * description: 自定义用户登录校验
 */
@Slf4j
@Service
public class IntegrationUserDetailsService implements UserDetailsService {

    private List<IntegrationAuthenticator> authenticators;

    @Autowired(required = false)
    public void setIntegrationAuthenticators(List<IntegrationAuthenticator> authenticators) {
        this.authenticators = authenticators;
    }

    @Override
    public AuthUserDetail loadUserByUsername(String username) throws UsernameNotFoundException {
        IntegrationAuthentication integrationAuthentication = IntegrationAuthenticationContext.get();

        //判断是否是集成登录
        if (integrationAuthentication == null) {
            integrationAuthentication = new IntegrationAuthentication();
        }
        integrationAuthentication.setUsername(username);

        try {
            AuthUserDetail user = this.authenticate(integrationAuthentication);
            if (user == null) {
                throw new UsernameNotFoundException("用户不存在");
            }

            return user;
        } catch (Exception e) {
            e.printStackTrace();
            throw new UsernameNotFoundException("用户名或密码错误");
        }

    }

    private AuthUserDetail authenticate(IntegrationAuthentication integrationAuthentication) throws Exception {
        if (this.authenticators != null) {
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    return authenticator.authenticate(integrationAuthentication);
                }
            }
        }
        return null;
    }
}
